package com.mflex.mwms.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

import androidx.annotation.NonNull;

import com.mflex.mwms.R;
import com.mflex.mwms.adapter.StockTaskDetailAdapter;
import com.mflex.mwms.model.CustomApiResult;
import com.mflex.mwms.model.DynamicStockRequest;
import com.mflex.mwms.model.ItemNumberStockRequest;
import com.mflex.mwms.model.LocationStockRequest;
import com.mflex.mwms.model.PackageStockRequest;
import com.mflex.mwms.model.StockDetailInfo;
import com.mflex.mwms.model.StockInfo;
import com.mflex.mwms.model.enumeration.StockType;
import com.mflex.mwms.utils.MMKVUtils;
import com.mflex.mwms.utils.MessageUtils;
import com.mflex.mwms.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class StockTaskListDetailActivity extends BaseActivity {
    @BindView(R.id.stv_TaskNo)
    EditText stvTaskNo;

    @BindView(R.id.stv_taskType)
    EditText stvTaskType;

    @BindView(R.id.stv_loc)
    EditText stvLoc;

    @BindView(R.id.stv_location)
    Spinner stvLocation;

    @BindView(R.id.stv_BoxNumber)
    EditText stvBoxNumber;

    @BindView(R.id.stv_Qty)
    EditText stvQty;

    @BindView(R.id.lvTaskList)
    ListView lvTaskList;

    @BindView(R.id.button_save)
    SuperButton buttonSave;

    @BindView(R.id.button_clear)
    SuperButton buttonClear;

    MiniLoadingDialog mMiniLoadingDialog;

    private List<String> taskList;

    private String userName;
    private String taskNo;

    private String[] locations;

    private StockInfo stockInfo;
    private List<StockDetailInfo> stockDetailInfos;

    int scanQty = 0;
    int totalQty = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stock_task_list_detail);

        ButterKnife.bind(this);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载中...");

        Intent intent = getIntent();
        userName = intent.getStringExtra("userName");
        taskNo = intent.getStringExtra("taskNo");


        stvTaskNo.setFocusable(false);
        stvTaskType.setFocusable(false);
        stvQty.setFocusable(false);
        stvBoxNumber.setOnKeyListener(this);
        stvLoc.setOnKeyListener(this);
        buttonSave.setOnClickListener(this);
        buttonClear.setOnClickListener(this);

        initData();

        stvLoc.requestFocus();

//        stvLocation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                if (StringUtils.isEmpty(locations[i])) {
//                    stvBoxNumber.setText("");
//                    stockDetailInfos = new ArrayList<>();
//                    StockTaskDetailAdapter stockTaskDetailAdapter = new StockTaskDetailAdapter(StockTaskListDetailActivity.this, stockDetailInfos);
//                    lvTaskList.setAdapter(stockTaskDetailAdapter);
//                } else {
//                    requestTaskDetail();
//                }
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> adapterView) {
//
//            }
//        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                clearButtonMd(view);
                break;
            case R.id.button_save:
                saveButtonMd(view);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_BoxNumber:
                    CheckBoxNumber(view);
                    break;
                case R.id.stv_loc:
                    if (!Arrays.asList(locations).contains(stvLoc.getText().toString())) {
//                        XToastUtils.error("输入的库位不是待盘库位!");
                        MessageUtils.errorMsgAndVoice(StockTaskListDetailActivity.this, "输入的库位不是待盘库位");
                        stvLoc.setText("");
                        stvLoc.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                stvLoc.requestFocus();
                            }
                        },200);
                        break;
                    }
                    requestTaskDetail();
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    private void initData() {
        mMiniLoadingDialog.show();
        XHttp.get("api/Stock/GetStockTask")
                .params("Warehouse", MMKVUtils.getString("Warehose", ""))
                .params("TaskNo", taskNo)
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<StockInfo>, StockInfo>(new SimpleCallBack<StockInfo>() {

                    @Override
                    public void onSuccess(StockInfo response) {
                        mMiniLoadingDialog.dismiss();
                        stockInfo = response;
                        List<String> locationList = new ArrayList();
                        locationList.addAll(response.getLocation());
                        locations = locationList.toArray(new String[0]);
                        WidgetUtils.initSpinnerStyle(stvLocation, locations);
                        stvTaskNo.setText(taskNo);
                        stvTaskType.setText(StockType.match(response.getStockType()).getValueStr());
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(StockTaskListDetailActivity.this)
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(StockTaskListDetailActivity.this)
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(StockTaskListDetailActivity.this, e);
                    }
                }) {
                });
    }

    private void requestTaskDetail() {
        mMiniLoadingDialog.show();
        XHttp.get("api/Stock/GetStockTaskDetail")
                .params("Warehouse", MMKVUtils.getString("Warehose", ""))
                .params("TaskNo", taskNo)
                .params("Location", stvLoc.getText().toString())


                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<List<StockDetailInfo>>, List<StockDetailInfo>>(new SimpleCallBack<List<StockDetailInfo>>() {

                    @Override
                    public void onSuccess(List<StockDetailInfo> response) {
                        mMiniLoadingDialog.dismiss();
                        stockDetailInfos = response;

                        StockTaskDetailAdapter stockTaskDetailAdapter = new StockTaskDetailAdapter(StockTaskListDetailActivity.this, stockDetailInfos);
                        lvTaskList.setAdapter(stockTaskDetailAdapter);

                        scanQty = 0;
                        totalQty = stockDetailInfos.size();
                        stvQty.setText(String.valueOf(scanQty) + "/" + String.valueOf(totalQty));

                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(StockTaskListDetailActivity.this)
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(StockTaskListDetailActivity.this)
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(StockTaskListDetailActivity.this, e);
                    }
                }) {
                });
    }

    private void CheckBoxNumber(View view) {
        if (StringUtils.isEmpty(stvLoc.getText().toString())) {
            XToastUtils.error("请先输入库位！", 3000);
            return;
        }
        boolean flag = false;
        boolean existFlag = false;
        for (StockDetailInfo stockDetailInfo : stockDetailInfos) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), stockDetailInfo.getBoxNumer()) && stockDetailInfo.isChecked()) {
                existFlag = true;
                break;
            }
        }
        if (existFlag) {
            stvBoxNumber.setText("");
            stvBoxNumber.requestFocus();
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱号已在列表中")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(StockTaskListDetailActivity.this, "箱号已在列表中");
            return;
        }
        for (StockDetailInfo stockDetailInfo : stockDetailInfos) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), stockDetailInfo.getBoxNumer())) {
                flag = true;
                stockDetailInfo.setChecked(true);
            }
        }
        if (!flag) {
            stvBoxNumber.setText("");
            stvBoxNumber.requestFocus();
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱号不在列表中")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(StockTaskListDetailActivity.this, "箱号不在列表中");
            stvBoxNumber.setText("");
            return;
        }

        Collections.sort(stockDetailInfos, new Comparator<StockDetailInfo>() {
            @Override
            public int compare(StockDetailInfo t0, StockDetailInfo t1) {
                if (!t0.isChecked() && t1.isChecked()) {
                    return -1;
                }
                return 0;
            }
        });

        StockTaskDetailAdapter stockTaskDetailAdapter = new StockTaskDetailAdapter(StockTaskListDetailActivity.this, stockDetailInfos);
        lvTaskList.setAdapter(stockTaskDetailAdapter);

        scanQty = scanQty + 1;
        stvQty.setText(String.valueOf(scanQty) + "/" + String.valueOf(totalQty));

        stvBoxNumber.setText("");
        stvBoxNumber.postDelayed(new Runnable() {
            @Override
            public void run() {
                stvBoxNumber.requestFocus();
            }
        }, 200);
    }

    private void clearButtonMd(View view) {
        stvLocation.setSelection(0);
        stvLoc.setText("");
        stvBoxNumber.setText("");
        stockDetailInfos = new ArrayList<>();
        StockTaskDetailAdapter stockTaskDetailAdapter = new StockTaskDetailAdapter(StockTaskListDetailActivity.this, stockDetailInfos);
        lvTaskList.setAdapter(stockTaskDetailAdapter);

        scanQty = 0;
        totalQty = 0;
        stvQty.setText("");
        XToastUtils.success("重置成功");
    }

    private void saveButtonMd(View view) {
        boolean checked = false;
        for (StockDetailInfo stockDetailInfo : stockDetailInfos) {
            if (!stockDetailInfo.isChecked()) {
                checked = true;
            }
        }
        if (checked) {
            new MaterialDialog.Builder(view.getContext())
                    .iconRes(R.drawable.icon_tip)
                    .title(R.string.tip_infos)
                    .content("有未盘点箱，是否继续提交")
                    .positiveText(R.string.lab_yes)
                    .negativeText(R.string.lab_no)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            submit(view);
                        }
                    })
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            return;
                        }
                    })
                    .cancelable(false)
                    .show();
        } else {
            submit(view);
        }
    }

    private void submit(View view) {
        if (StringUtils.equals(stockInfo.getStockType(), StockType.DYNAMIC.getCode())) {
            DynamicStockRequest dynamicStockRequest = new DynamicStockRequest();
            List<String> dynaicList = new ArrayList<>();
            for (StockDetailInfo stockDetailInfo : stockDetailInfos) {
                if (stockDetailInfo.isChecked()) {
                    dynaicList.add(stockDetailInfo.getBoxNumer());
                }
            }
            dynamicStockRequest.setTaskNo(taskNo);
            dynamicStockRequest.setWarehouse(MMKVUtils.getString("Warehose", ""));
            dynamicStockRequest.setLocation(stvLoc.getText().toString());
            dynamicStockRequest.setBoxNumber(dynaicList);
            mMiniLoadingDialog.show();
            XHttp.post("api/Stock/DynamicStock")
                    .upJson(JsonUtil.toJson(dynamicStockRequest))
                    .syncRequest(false)
                    .onMainThread(true)
                    .accessToken(true)
                    .timeOut(120000)
                    .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                        @Override
                        public void onSuccess(String response) {
                            mMiniLoadingDialog.dismiss();
//                                                requestTaskDetail();
                            StockTaskDetailAdapter stockTaskDetailAdapter = new StockTaskDetailAdapter(StockTaskListDetailActivity.this, new ArrayList<>());
                            lvTaskList.setAdapter(stockTaskDetailAdapter);
                            scanQty = 0;
                            totalQty = 0;
                            stvQty.setText("");
                            if (locations.length > 1) {
                                XToastUtils.success("提交成功！");
                                initData();
                            } else {
                                XToastUtils.success("盘点全部完成");
                                back();
                            }

                        }

                        @Override
                        public void onError(ApiException e) {
                            mMiniLoadingDialog.dismiss();
                            stvBoxNumber.setText("");
                            stvBoxNumber.requestFocus();
//                            if (e.getCode() == 100) {
//                                new MaterialDialog.Builder(view.getContext())
//                                        .iconRes(R.drawable.icon_warning)
//                                        .title(R.string.tip_warning)
//                                        .content(e.getMessage())
//                                        .positiveText(R.string.lab_submit)
//                                        .show();
//                            }
//                            if (e.getCode() == 200) {
//                                new MaterialDialog.Builder(view.getContext())
//                                        .iconRes(R.drawable.icon_tip)
//                                        .title(R.string.tip_infos)
//                                        .content(e.getMessage())
//                                        .positiveText(R.string.lab_submit)
//                                        .show();
//                            }
                            MessageUtils.errorMsgAndVoice(StockTaskListDetailActivity.this, e);
                        }
                    }) {
                    });
        } else if (StringUtils.equals(stockInfo.getStockType(), StockType.ITEMNUMMER.getCode())) {
            ItemNumberStockRequest itemNumberStockRequest = new ItemNumberStockRequest();
            List<String> dynaicList = new ArrayList<>();
            for (StockDetailInfo stockDetailInfo : stockDetailInfos) {
                if (stockDetailInfo.isChecked()) {
                    dynaicList.add(stockDetailInfo.getBoxNumer());
                }
            }
            itemNumberStockRequest.setTaskNo(taskNo);
            itemNumberStockRequest.setWarehouse(MMKVUtils.getString("Warehose", ""));
            itemNumberStockRequest.setLocation(stvLoc.getText().toString());
            itemNumberStockRequest.setBoxNumber(dynaicList);
            mMiniLoadingDialog.show();
            XHttp.post("api/Stock/ItemNumberStock")
                    .upJson(JsonUtil.toJson(itemNumberStockRequest))
                    .syncRequest(false)
                    .onMainThread(true)
                    .accessToken(true)
                    .timeOut(120000)
                    .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                        @Override
                        public void onSuccess(String response) {
                            mMiniLoadingDialog.dismiss();
                            //                                                requestTaskDetail();
                            StockTaskDetailAdapter stockTaskDetailAdapter = new StockTaskDetailAdapter(StockTaskListDetailActivity.this, new ArrayList<>());
                            lvTaskList.setAdapter(stockTaskDetailAdapter);
                            scanQty = 0;
                            totalQty = 0;
                            stvQty.setText("");
                            if (locations.length > 1) {
                                XToastUtils.success("提交成功！");
                                initData();
                            } else {
                                XToastUtils.success("盘点全部完成");
                                back();
                            }
                        }

                        @Override
                        public void onError(ApiException e) {
                            mMiniLoadingDialog.dismiss();
                            stvBoxNumber.setText("");
                            stvBoxNumber.requestFocus();
//                            if (e.getCode() == 100) {
//                                new MaterialDialog.Builder(view.getContext())
//                                        .iconRes(R.drawable.icon_warning)
//                                        .title(R.string.tip_warning)
//                                        .content(e.getMessage())
//                                        .positiveText(R.string.lab_submit)
//                                        .show();
//                            }
//                            if (e.getCode() == 200) {
//                                new MaterialDialog.Builder(view.getContext())
//                                        .iconRes(R.drawable.icon_tip)
//                                        .title(R.string.tip_infos)
//                                        .content(e.getMessage())
//                                        .positiveText(R.string.lab_submit)
//                                        .show();
//                            }
                            MessageUtils.errorMsgAndVoice(StockTaskListDetailActivity.this, e);
                        }
                    }) {
                    });
        } else if (StringUtils.equals(stockInfo.getStockType(), StockType.LOCATION.getCode())) {
            LocationStockRequest locationStockRequest = new LocationStockRequest();
            List<String> dynaicList = new ArrayList<>();
            for (StockDetailInfo stockDetailInfo : stockDetailInfos) {
                if (stockDetailInfo.isChecked()) {
                    dynaicList.add(stockDetailInfo.getBoxNumer());
                }
            }
            locationStockRequest.setTaskNo(taskNo);
            locationStockRequest.setWarehouse(MMKVUtils.getString("Warehose", ""));
            locationStockRequest.setBoxNumber(dynaicList);
            locationStockRequest.setLocation(stvLoc.getText().toString());
            mMiniLoadingDialog.show();
            XHttp.post("api/Stock/LocationStock")
                    .upJson(JsonUtil.toJson(locationStockRequest))
                    .syncRequest(false)
                    .onMainThread(true)
                    .accessToken(true)
                    .timeOut(120000)
                    .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                        @Override
                        public void onSuccess(String response) {
                            mMiniLoadingDialog.dismiss();

                            //                                                requestTaskDetail();
                            StockTaskDetailAdapter stockTaskDetailAdapter = new StockTaskDetailAdapter(StockTaskListDetailActivity.this, new ArrayList<>());
                            lvTaskList.setAdapter(stockTaskDetailAdapter);
                            scanQty = 0;
                            totalQty = 0;
                            stvQty.setText("");
                            if (locations.length > 1) {
                                XToastUtils.success("提交成功！");
                                initData();
                            } else {
                                XToastUtils.success("盘点全部完成");
                                back();
                            }
                        }

                        @Override
                        public void onError(ApiException e) {
                            mMiniLoadingDialog.dismiss();
                            stvBoxNumber.setText("");
                            stvBoxNumber.requestFocus();
                            MessageUtils.errorMsgAndVoice(StockTaskListDetailActivity.this, e);
                        }
                    }) {
                    });
        } else if (StringUtils.equals(stockInfo.getStockType(), StockType.PKG.getCode())) {
            PackageStockRequest packageStockRequest = new PackageStockRequest();
            List<String> pkgList = new ArrayList<>();
            for (StockDetailInfo stockDetailInfo : stockDetailInfos) {
                if (stockDetailInfo.isChecked()) {
                    pkgList.add(stockDetailInfo.getBoxNumer());
                }
            }
            packageStockRequest.setTaskNo(taskNo);
            packageStockRequest.setWarehouse(MMKVUtils.getString("Warehose", ""));
            packageStockRequest.setBoxNumber(pkgList);
            packageStockRequest.setLocation(stvLoc.getText().toString());
            mMiniLoadingDialog.show();
            XHttp.post("api/Stock/PackageStock")
                    .upJson(JsonUtil.toJson(packageStockRequest))
                    .syncRequest(false)
                    .onMainThread(true)
                    .accessToken(true)
                    .timeOut(120000)
                    .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                        @Override
                        public void onSuccess(String response) {
                            mMiniLoadingDialog.dismiss();
                            StockTaskDetailAdapter stockTaskDetailAdapter = new StockTaskDetailAdapter(StockTaskListDetailActivity.this, new ArrayList<>());
                            lvTaskList.setAdapter(stockTaskDetailAdapter);
                            scanQty = 0;
                            totalQty = 0;
                            stvQty.setText("");
                            if (locations.length > 1) {
                                XToastUtils.success("提交成功！");
                                initData();
                            } else {
                                XToastUtils.success("盘点全部完成");
                                back();
                            }
                        }

                        @Override
                        public void onError(ApiException e) {
                            mMiniLoadingDialog.dismiss();
                            stvBoxNumber.setText("");
                            stvBoxNumber.requestFocus();
                            MessageUtils.errorMsgAndVoice(StockTaskListDetailActivity.this, e);
                        }
                    }) {
                    });
        }
    }

    private void back() {
        setResult(0);
        finish();
    }
}